const express = require("express");
const fs = require("fs");
const app = express();
//中间件
app.use(express.static("./www"));

// 中间件 处理GET请求
app.use((req, res, next) => {
  if (req.method === "GET") {
    fs.readFile("./www/a.txt", (err, data) => {
      if (err === null) {
        res.send(data.toString());
      } else {
        res.send(err.message);
      }
    });
  } else {
    next();
  }
});
// 中间件 处理POST请求
app.use((req, res, next) => {
  if (req.method === "POST") {
    fs.writeFile("./www/a.txt", "hello jack", (err) => {
      if (err === null) {
        res.send("hello POST success");
      } else {
        res.send(err.message);
      }
    });
  } else {
    next();
  }
});
// 中间件 处理PUT请求
app.use((req, res, next) => {
  if (req.method === "PUT") {
    fs.writeFile("./www/a.txt", "hello lili", (err) => {
      if (err === null) {
        res.send("hello PUT success");
      } else {
        res.send(err.message);
      }
    });
  } else {
    next();
  }
});
// 中间件 处理 DELETE 请求
app.use((req, res, next) => {
  if (req.method === "DELETE") {
    fs.unlink("./www/a.txt", (err) => {
      if (err === null) {
        res.send("hello DELETE success");
      } else {
        res.send(err.message);
      }
    });
  } else {
    next();
  }
});

// 设置端口
const port = 3009;
app.listen(port, () => {
  console.log(`http://192.168.1.42:${port}`);
});
